<?php
namespace basic\services;


use think\exception\ValidateException;

class LocationSearchService{


    /**
     * 地图 1-腾讯  2-高德 3-百度
     * @var string
     */
    protected $mapType = '';

    protected $keyTx = '';
    protected $keyBD = '';
    protected $keyGD = '';

    protected $searchArr = [];


    protected $data = [];

    protected $count = 0;

    protected $page = 1;

    protected $continueStatus = true;


    public function __construct($mapType = '')
    {
        $this->mapType = $mapType;
        if($mapType == 1){
            $this->keyTx = env('MAPKEY.TX_MAP_KEY');
        }elseif ($mapType ==2 ){
            $this->keyGD = env('MAPKEY.GD_MAP_KEY');
        }elseif ($mapType == 3){
            $this->keyBD = env('MAPKEY.BD_MAP_KEY');
        }
    }


    public static function create($mapType = 1)
    {
       return new static($mapType);
    }


    public function searchLocation($searchArr)
    {
        $this->searchArr = $searchArr;
        $map = [
          1 => 'searchTX',
          2 => 'searchGD',
          3 => 'searchBD'
        ];
        $method = $map[$this->mapType ?: 1];
        $this->count = $this->searchArr['count'];

        $tryCount = 15;
        while ($tryCount > 0){
            if(count($this->data) >= $this->count || !$this->continueStatus){
                break;
            }
            $this->$method();
            $this->page ++;
            $tryCount --;
        }

        return  $this->data;
    }



    public function searchTX()
    {
        if($this->searchArr['search_type'] == 1){
            // 城市/区域搜索
            $boundary = "region({$this->searchArr['city']},1,0,0)";

            $url = "https://apis.map.qq.com/ws/place/v1/search";
            $data = [
                'key'=> $this->keyTx,
                'keyword'=>$this->searchArr['keywords'],
                'boundary'=>$boundary,
                'page_size'=>20,
                'page_index'=>$this->page,
            ];
        }else{
            // 周边搜索
            $range = $this->searchArr['range']*1000;
            $boundary = "nearby({$this->searchArr['lat']},{$this->searchArr['lng']},{$range},1)";

            $url = "https://apis.map.qq.com/ws/place/v1/search";
            $data = [
                'key'=> $this->keyTx,
                'keyword'=>$this->searchArr['keywords'],
                'boundary'=>$boundary,
                'page_size'=>20,
                'page_index'=>$this->page,
            ];
        }

        try {
            $rs = HttpService::getRequest($url,$data);
            $info = json_decode($rs,true);

          //  var_dump($rs);

        }catch (\Exception $exception){
            throw new ValidateException('腾讯接口异常-'.$exception->getMessage());
        }

        if(!isset($info['status']) || $info['status'] != 0){
            throw new ValidateException('腾讯接口异常-'.($info['message'] ?? '失败!'));
        }

        $mapInfos = $info['data'] ?? [];
        if(!$mapInfos || !count($mapInfos)){
            $this->continueStatus = false;
            return;
        }

        foreach ($mapInfos as $mapInfo){
            $tmp = [
                'phone'=>$mapInfo['tel'] ?? '',
                'name'=>$mapInfo['title']??'',
                'tags'=>$mapInfo['category']??'',
                'province'=>$mapInfo['ad_info']['province']??'',
                'city'=>$mapInfo['ad_info']['city']??'',
                'region'=>$mapInfo['ad_info']['district']??'',
                'address'=>$mapInfo['address']??'',
                'lng'=>$mapInfo['location']['lng']??'',
                'lat'=>$mapInfo['location']['lat']??'',
            ];


            if($this->searchArr['filter'] != 0 && !$tmp['phone']){
                continue;
            }


            if ($this->searchArr['filter'] == 2){
                if(strpos($tmp['phone'],'-') !== false){
                    continue;
                }
            }

            if ($this->searchArr['filter'] == 3){
                if(strpos($tmp['phone'],'-') === false){
                    continue;
                }
            }

            $this->data[] = $tmp;
            if(count($this->data) >= $this->count){
                $this->continueStatus = false;
                break;
            }
        }
    }



    public function searchGD()
    {
        // 全城搜索 poi2.0
        if($this->searchArr['search_type'] == 1){
            // 关键字搜索
            $url = "https://restapi.amap.com/v5/place/text?parameters";
            $data = [
                'key'=> $this->keyGD,
                'keywords'=>$this->searchArr['keywords'],
                'types'=>'',
                'region'=>$this->searchArr['city'],
                'page_size'=>20,
                'page_num'=>$this->page,
                'show_fields'=>'business,photos',
            ];
        }else{
            // 周边搜索
            $url = "https://restapi.amap.com/v5/place/around?parameters";
            $data = [
                'key'=> $this->keyGD,
                'keywords'=>$this->searchArr['keywords'],
                'types'=>'',
                'location'=>$this->searchArr['lng'].','.$this->searchArr['lat'],
                'radius'=>$this->searchArr['range']*1000,
                'region'=>$this->searchArr['city'],
                'page_size'=>20,
                'page_num'=>1,
                'show_fields'=>'business,photos',
            ];
        }


        try {
            $rs = HttpService::getRequest($url,$data);
            $info = json_decode($rs,true);
        }catch (\Exception $exception){
            throw new ValidateException('高德接口异常-'.$exception->getMessage());
        }

        if(!isset($info['status']) || $info['status'] != 1){
            throw new ValidateException('高德接口异常-'.($info['info'] ?? '失败!'));
        }


        $info = json_decode($rs,true);

        $mapInfos = $info['pois'] ?? [];
        if(!$mapInfos || !count($mapInfos)){
            $this->continueStatus = false;
            return;
        }

        foreach ($mapInfos as $mapInfo){

            $location = $mapInfo['location'] ? explode(',',$mapInfo['location']) : [];

            $tmp = [
                'phone'=>$mapInfo['business']['tel'] ?? '',
                'name'=>$mapInfo['name']??'',
                'tags'=>$mapInfo['business']['keytag'] ?? ($mapInfo['type']??''),
                'province'=>$mapInfo['pname']??'',
                'city'=>$mapInfo['cityname']??'',
                'region'=>$mapInfo['adname']??'',
                'address'=>$mapInfo['address']??'',
                'lng'=>$location[0]??'',
                'lat'=>$location[1]??''
            ];


            if($this->searchArr['filter'] != 0 && !$tmp['phone']){
                continue;
            }


            if ($this->searchArr['filter'] == 2){
                if(strpos($tmp['phone'],'-') !== false){
                    continue;
                }
            }

            if ($this->searchArr['filter'] == 3){
                if(strpos($tmp['phone'],'-') === false){
                    continue;
                }
            }

            $this->data[] = $tmp;
            if(count($this->data) >= $this->count){
                $this->continueStatus = false;
                break;
            }
        }
    }



    public function searchBD()
    {
        if($this->searchArr['search_type'] == 1){
            // 行政区划区域检索
            $url = "https://api.map.baidu.com/place/v2/search";
            $data = [
                'ak'=> $this->keyBD,
                'query'=>$this->searchArr['keywords'],
                'region'=>$this->searchArr['city'],
                'radius'=>$this->searchArr['range']*1000,
                'scope'=>2,
                'page_size'=>20,
                'page_num'=>1,

                'output'=>'json',
            ];
        }else{
            // 周边搜索 圆形区域检索
            $url = "https://api.map.baidu.com/place/v2/search";
            $data = [
                'ak'=> $this->keyBD,
                'query'=>$this->searchArr['keywords'],
                'location'=>$this->searchArr['lat'].','.$this->searchArr['lng'],
                'radius'=>$this->searchArr['range']*1000,
                'page_size'=>20,
                'page_num'=>1,
                'scope'=>2,
                'output'=>'json',
            ];
        }

        try {
            $rs = HttpService::getRequest($url,$data);
            $info = json_decode($rs,true);
        }catch (\Exception $exception){
            throw new ValidateException('百度接口异常-'.$exception->getMessage());
        }

        if(!isset($info['status']) || $info['status'] != 0){
            throw new ValidateException('百度接口异常-'.($info['message'] ?? '失败!'));
        }

        $mapInfos = $info['results'] ?? [];


        if(!$mapInfos || !count($mapInfos)){
            $this->continueStatus = false;
            return;
        }

        foreach ($mapInfos as $mapInfo){
            $tmp = [
                'phone'=>$mapInfo['telephone'] ?? '',
                'name'=>$mapInfo['name']??'',
                'tags'=>$mapInfo['detail_info']['label'] ?? '',
                'province'=>$mapInfo['province']??'',
                'city'=>$mapInfo['city']??'',
                'region'=>$mapInfo['area']??'',
                'address'=>$mapInfo['address']??'',
                'lng'=>$mapInfo['location']['lng']??'',
                'lat'=>$mapInfo['location']['lat']??'',
            ];


            if($this->searchArr['filter'] != 0 && !$tmp['phone']){
                continue;
            }


            if ($this->searchArr['filter'] == 2){
                if(strpos($tmp['phone'],'(') !== false){
                    continue;
                }
            }

            if ($this->searchArr['filter'] == 3){
                if(strpos($tmp['phone'],'(') === false){
                    continue;
                }
            }

            $this->data[] = $tmp;
            if(count($this->data) >= $this->count){
                $this->continueStatus = false;
                break;
            }
        }
    }



}
